 /**
 * DISCLIMER: 
 * this library is an opensource, feel free to edit or redistribute it
 * but use it with you own risk
 * 
 * ktutnik
 */
package org.ticlib.task
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	
	public class ResourceLoader extends Task
	{
		[Bindable] public var url:String;
		[Bindable] public var resultConverter:Function;
		
		private var loader:URLLoader;
		
		public function ResourceLoader()
		{
			super();
			
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
		}
		
		override public function execute():void
		{
			initialize();
			try
			{
				loader.load(new URLRequest(url));
			}
			catch (e:Error)
			{
				faultObject = new Fault("", e.message);
				dispatchEvent(FaultEvent.createEvent(faultObject as Fault));
			}
		}
		
		override public function stop():void
		{
			if(!isComplete)
			{
				loader.close();
				isComplete = true;
			}
			if((chain) && (!chain.isComplete))
				chain.stop();
			dispatchEvent(new Event(Event.CANCEL));
		}
		
		private function onComplete(e:Event):void
		{
			if(resultConverter != null)
				resultConverter.apply(this, [loader.data]);
			else
				resultObject = loader.data;
			isComplete = true;
			dispatchEvent(new Event(Event.COMPLETE));
			
			if((chain) && (!parent.isComplete)) chain.execute();
		}
		
		private function onError(e:IOErrorEvent):void
		{
			faultObject = new Fault("", e.text);
			dispatchEvent(FaultEvent.createEvent(faultObject as Fault));
		}
		
		private function onSecurityError(e:SecurityErrorEvent):void
		{
			faultObject = new Fault("", e.text);
			dispatchEvent(FaultEvent.createEvent(faultObject as Fault));
		}
	}
}